<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>客户界面</title>
    <link rel="stylesheet" href="element-ui/lib/theme-chalk/index.css">
    <script src="js/vue.js"></script>
    <script src="element-ui/lib/index.js"></script>
    <script src="js/axios-0.18.0.js"></script>
</head>
<body>
<div id="app">
    <el-row type="flex" justify="space-between" align="middle">
        <el-col :span="1">
            <el-row type="flex" align="middle" :gutter="20">
                <el-col>
                    <div>
                        <el-avatar v-if="client.avatar" :src="imageUrl"></el-avatar>
                        <el-avatar v-else icon="el-icon-user-solid"></el-avatar>
                    </div>
                </el-col>
                <el-col>
                    <el-button plain>
                        <a v-if="isLoggedIn" @click="goToMyInformation">{{ client.nickname }}</a>
                        <a v-else @click="goToLogin">登录</a>
                    </el-button>
                </el-col>
            </el-row>
        </el-col>
        <span v-if="client.status === '封禁'"
              style="color: #ff4d4f; margin-left: 12px;">您已被封禁，无法下单和支付，请联系管理员：xxxxx</span>
        <el-col :span="12" style="text-align: right;">
            <el-button
                    v-if="isLoggedIn"
                    type="danger"
                    plain
                    @click="logout"
                    style="margin-left: 10px;">
                退出登录
            </el-button>
        </el-col>
    </el-row>
    <template>
        <el-tabs value="first" @tab-click="handleClick">
            <el-tab-pane label="店铺" name="first">
                <el-row style="margin-top: 20px;">
                    <el-col :span="10">
                        <el-input v-model="shop.tradeName" placeholder="请输入店名"></el-input>
                    </el-col>
                    <el-col :span="2" style="margin-left: 10px;">
                        <el-button type="primary" @click="fetchShops">搜索</el-button>
                    </el-col>
                </el-row>
                <el-table :data="shops" style="margin-top: 20px;" border>
                    <el-table-column type="expand">
                        <template slot-scope="props">
                            <el-form label-position="left">
                                <el-form-item label="店铺名称：">
                                    <span>{{ props.row.tradeName }}</span>
                                </el-form-item>
                                <el-form-item label="店铺地址：">
                                    <span>{{ props.row.address }}</span>
                                </el-form-item>
                                <el-form-item label="联系方式：">
                                    <span>{{ props.row.contact }}</span>
                                </el-form-item>
                                <el-form-item label="关键词：">
                                    <span>{{ props.row.keyword }}</span>
                                </el-form-item>
                                <el-form-item label="销量：">
                                    <span>{{ props.row.totalSales }}</span>
                                </el-form-item>
                                <el-form-item label="浏览量：">
                                    <span>{{ props.row.view }}</span>
                                </el-form-item>
                                <el-form-item label="发布时间：">
                                    <span>{{ props.row.date }}</span>
                                </el-form-item>
                            </el-form>
                        </template>
                    </el-table-column>
                    <el-table-column prop="tradeName" label="店名" sortable></el-table-column>
                    <el-table-column prop="keyword" label="关键词"></el-table-column>
                    <el-table-column prop="totalSales" label="销量" sortable></el-table-column>
                    <el-table-column prop="view" label="浏览量" sortable></el-table-column>
                    <el-table-column prop="date" label="发布时间" sortable></el-table-column>
                    <el-table-column label="操作">
                        <template slot-scope="scope">
                            <el-button size="mini" @click="showRoomDetails(scope.row)">查看</el-button>
                            <el-button
                                    type="text"
                                    @click="handleFavorite(scope.row)"
                                    :icon="scope.row.favour ? 'el-icon-star-on' : 'el-icon-star-off'"
                                    :style="{color: scope.row.favour ? '#ffc107' : '#999'}">
                            </el-button>
                            <el-button size="mini" type="danger" @click="blockShop(scope.row)">拉黑</el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <el-pagination
                        background
                        @size-change="handleSizeChange"
                        @current-change="handleCurrentChange"
                        :current-page="currentPage"
                        :page-sizes="[5, 10, 20, 50]"
                        :page-size="pageSize"
                        layout="total, sizes, prev, pager, next, jumper"
                        :total="totalShops">
                    style="margin-top: 20px;">
                </el-pagination>
            </el-tab-pane>


            <el-tab-pane label="我的订单" name="second">
                <el-table :data="orders" style="margin-top: 20px;" border v-if="isLoggedIn">
                    <el-table-column prop="date" label="时间" width="180" sortable></el-table-column>
                    <el-table-column prop="merchantName" label="店铺"></el-table-column>
                    <el-table-column prop="roomName" label="房型"></el-table-column>
                    <el-table-column prop="roomNumber" label="房间号"></el-table-column>
                    <el-table-column prop="amount" label="金额"></el-table-column>
                    <el-table-column prop="tradeStatus" label="交易状态" sortable></el-table-column>
                    <el-table-column prop="checkStatus" label="入住状态" sortable></el-table-column>
                    <el-table-column label="操作" width="180">
                        <template slot-scope="scope">
                            <div v-if="scope.row.tradeStatus === '待支付'">
                                <el-button size="mini" @click="goToPayment(scope.row)">去支付</el-button>
                                <el-button size="mini" type="danger" @click="cancelOrder(scope.row)">取消订单
                                </el-button>
                            </div>
                            <div v-else-if="scope.row.tradeStatus === '已支付' && scope.row.checkStatus === '未入住'">
                                <el-button size="mini" @click="requestRefund(scope.row)">申请退款</el-button>
                            </div>
                            <div v-else-if="(scope.row.tradeStatus === '已支付' && scope.row.checkStatus === '已退房') || scope.row.tradeStatus === '已取消' || scope.row.tradeStatus === '已退款'">
                                <el-button size="mini" type="danger" @click="deleteOrder(scope.row)">删除订单
                                </el-button>
                            </div>
                        </template>
                    </el-table-column>
                </el-table>
                <el-alert v-else title="请先登录" type="warning" show-icon style="margin-top: 20px;"></el-alert>
            </el-tab-pane>
        </el-tabs>
    </template>


    <!-- 弹窗 -->
    <el-dialog title="房型信息" :visible.sync="dialogVisible">
        <el-table :data="selectedRoomDetails" border>
            <el-table-column type="expand">
                <template slot-scope="props">
                    <el-form label-position="left">
                        <el-form-item label="关键词：">
                            <span>{{ props.row.keyword }}</span>
                        </el-form-item>
                        <el-form-item label="床型：">
                            <span>{{ props.row.bedType }}</span>
                        </el-form-item>
                        <el-form-item label="设施：">
                            <span>{{ props.row.facility }}</span>
                        </el-form-item>
                        <el-form-item label="面积：">
                            <span>{{ props.row.area }}</span>
                        </el-form-item>
                        <el-form-item label="人数：">
                            <span>{{ props.row.capacity }}</span>
                        </el-form-item>
                        <el-form-item label="价格：">
                            <span>{{ props.row.price }}</span>
                        </el-form-item>
                        <el-form-item label="销量：">
                            <span>{{ props.row.salesVolume }}</span>
                        </el-form-item>
                        <el-form-item label="剩余数量：">
                            <span>{{ props.row.surplus }}</span>
                        </el-form-item>
                    </el-form>
                </template>
            </el-table-column>
            <el-table-column prop="keyword" label="关键词" sortable></el-table-column>
            <el-table-column prop="capacity" label="人数" sortable></el-table-column>
            <el-table-column prop="price" label="价格" sortable></el-table-column>
            <el-table-column prop="surplus" label="剩余数量" sortable></el-table-column>
            <el-table-column label="操作">
                <template slot-scope="scope">
                    <el-button size="mini" type="primary" @click="openRoomNumberDialog(scope.row)">房间号</el-button>
                </template>
            </el-table-column>
        </el-table>
    </el-dialog>

    <el-dialog title="支付验证" :visible.sync="dialogVisibleForPayment" width="30%">
        <el-input
                type="password"
                v-model="password"
                placeholder="请输入登录密码"
                @keyup.enter.native="handlePayment"
        ></el-input>
        <span slot="footer">
        <el-button @click="dialogVisibleForPayment = false">取消</el-button>
        <el-button type="primary" @click="handlePayment">确认支付</el-button>
    </span>
    </el-dialog>

    <el-dialog title="房间号" :visible.sync="roomNumberDialogVisible" width="50%">
        <el-table :data="roomNumbers" border v-if="roomNumbers.length > 0">
            <el-table-column prop="roomNumber" label="房间号"></el-table-column>
            <el-table-column prop="status" label="状态" sortable></el-table-column>
            <el-table-column label="操作">
                <template slot-scope="scope">
                    <el-button size="mini" :disabled="scope.row.status === '不可用'" @click="placeOrder(scope.row)">下单
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
        <div v-else style="text-align: center; margin-top: 20px;">暂无房间号</div>
    </el-dialog>
</div>

<script>
    new Vue({
        el: '#app',
        data() {
            return {
                isLoggedIn: false, // 登录状态
                user: {
                    id: 0,
                    phoneNum: '',
                    password: '',
                    userType: ''
                },
                client: {
                    id: 0,
                    userId: '',
                    nickName: '',
                    idNum: '',
                    balance: '',
                    coin: '',
                    avatar: '',
                    status: '正常'
                },
                shop: {
                    tradeName: ''
                },
                shops: [], // 店铺数据
                orders: [], // 订单数据
                totalShops: 0, // 总店铺数
                pageSize: 5, // 每页显示数量
                currentPage: 1, // 当前页码
                dialogVisible: false, // 弹窗显示状态
                selectedRoomDetails: [],
                dialogVisibleForPayment: false,
                password: '',
                currentOrder: null,
                roomNumberDialogVisible: false,
                roomNumbers: [], // 房间号数据
                imageUrl: '',
            };
        },
        async mounted() {
            await this.checkLoginStatus();
        },
        methods: {
            // 检查登录状态
            checkLoginStatus() {
                const _this = this;
                _this.fetchShops();
                axios.get('http://localhost:8080/ProjectRound1_war/user/checkLogin').then(response => {
                    if (response.data.code === 200 && response.data.data.user.userType === "client") {
                        _this.isLoggedIn = true;
                        _this.user = response.data.data.user;
                        _this.client = response.data.data.additionalInfo;
                        _this.imageUrl = `/ProjectRound1_war/img/avatar/${_this.client.avatar}`;
                        _this.fetchShops();
                        _this.fetchOrders();
                    } else {
                        _this.isLoggedIn = false;
                    }
                });
            },
            logout() {
                if (!this.isLoggedIn) {
                    window.location.href = 'login.html';
                }
                if (!confirm('确定要退出登录吗？')) {
                    return;
                }
                const _this = this;
                axios.post('http://localhost:8080/ProjectRound1_war/user/logout')
                    .then(() => {
                        _this.isLoggedIn = false;
                        _this.user = {};
                        _this.client = {};
                        alert('退出登录成功');
                        window.location.reload();
                    });
            },
            // 获取店铺数据
            fetchShops() {
                const _this = this;
                axios.post('http://localhost:8080/ProjectRound1_war/client/queryMerchant?currentPage=' + _this.currentPage + '&pageSize=' + _this.pageSize, {
                    clientId: _this.client.id,
                    tradeName: _this.shop.tradeName,
                }).then(response => {
                    if (response.data.code === 200) {
                        _this.shops = response.data.data.rows;
                        _this.totalShops = response.data.data.totalCount;
                    } else {
                        console.error('获取店铺数据失败:', response.data.msg);
                    }
                });
            },

            // 获取订单数据
            fetchOrders() {
                if (!this.isLoggedIn) {
                    window.location.href = 'login.html';
                    return;
                }
                const _this = this;
                axios.post('http://localhost:8080/ProjectRound1_war/client/queryOrder', _this.user)
                    .then(response => {
                        if (response.data.code === 200) {
                            _this.orders = response.data.data;
                        } else {
                            _this.$message.error('获取订单数据失败');
                        }
                    })
                    .catch(error => {
                        console.error('请求失败:', error);
                        _this.$message.error('获取订单数据失败');
                    });
            },

            // 分页
            handleSizeChange(val) {
                this.pageSize = val;
                this.fetchShops();
            },
            handleCurrentChange(val) {
                this.currentPage = val;
                this.fetchShops();
            },

            handleFavorite(merchant) {
                if (!this.isLoggedIn) {
                    window.location.href = 'login.html';
                }
                if (merchant.favour === true) {
                    this.cancelFavorite(merchant);
                } else {
                    this.favoriteShop(merchant);
                }
            },

            // 收藏店铺
            favoriteShop(merchant) {
                if (!this.isLoggedIn) {
                    window.location.href = 'login.html';
                    return;
                }
                const _this = this;
                axios.post('http://localhost:8080/ProjectRound1_war/client/favourMerchant', {
                    clientId: _this.client.id,
                    merchantId: merchant.id,
                })
                    .then(response => {
                        if (response.data.code === 200) {
                            _this.$message.success('收藏成功！');
                            _this.fetchShops(); // 刷新店铺列表
                        } else {
                            _this.$message.error('收藏失败');
                            console.error(response.data.msg);
                        }
                    })
                    .catch(error => {
                        console.error('请求失败:', error);
                        _this.$message.error('收藏失败');
                    });
            },

            // 取消收藏店铺
            cancelFavorite(merchant) {
                if (!this.isLoggedIn) {
                    window.location.href = 'login.html';
                }
                const _this = this;
                axios.post('http://localhost:8080/ProjectRound1_war/client/cancelFavour', {
                    clientId: _this.client.id,
                    merchantId: merchant.id,
                })
                    .then(response => {
                        if (response.data.code === 200) {
                            _this.$message.success('取消收藏成功！');
                            _this.fetchShops(); // 刷新店铺列表
                        } else {
                            _this.$message.error('取消收藏失败');
                            console.error(response.data.msg);
                        }
                    })
                    .catch(error => {
                        console.error('请求失败:', error);
                        _this.$message.error('收藏失败');
                    });
            },

            // 拉黑店铺
            blockShop(merchant) {
                // 新增确认提示
                if (!confirm('确定要将该店铺加入黑名单吗？')) {
                    return;
                }
                if (!this.isLoggedIn) {
                    window.location.href = 'login.html';
                    return;
                }
                const _this = this;
                axios.post('http://localhost:8080/ProjectRound1_war/client/blackMerchant', {
                    clientId: _this.client.id,
                    merchantId: merchant.id,
                })
                    .then(response => {
                        if (response.data.code === 200) {
                            _this.$message.success('已拉黑');
                            _this.fetchShops(); // 刷新店铺列表
                        } else {
                            _this.$message.error(response.data.msg);
                        }
                    })
                    .catch(error => {
                        console.error('请求失败:', error);
                        _this.$message.error('拉黑失败');
                    });
            },

            // 跳转到个人信息页面
            goToMyInformation() {
                window.location.href = 'client_info.html';
            },

            // 跳转到登录页面
            goToLogin() {
                window.location.href = 'login.html';
            },

            // 处理标签页切换
            handleClick(tab) {
                if (tab.name === 'second') {
                    this.fetchOrders();
                } else if (tab.name === 'first') {
                    this.fetchShops();
                }
            },

            showRoomDetails(merchant) {
                this.addOrUpdateBrowse(merchant);
                const merchantId = merchant.id;
                const _this = this;
                axios.post('http://localhost:8080/ProjectRound1_war/merchant/queryRoom', merchantId)
                    .then(response => {
                        if (response.data.code === 200) {
                            _this.selectedRoomDetails = response.data.data;
                        }
                    })
                    .catch(error => {
                        console.error('请求失败:', error);
                        _this.$message.error('获取房型信息失败');
                    });
                this.dialogVisible = true;
            },

            addOrUpdateBrowse(merchant) {
                if (!this.isLoggedIn) {
                    return;
                }
                const merchantId = merchant.id;
                const _this = this;
                axios.post('http://localhost:8080/ProjectRound1_war/browse/addOrUpdateBrowse', {
                    clientId: _this.client.id,
                    merchantId: merchantId,
                })
                    .then(response => {
                        if (response.data.code === 200) {
                            console.log('浏览记录添加或更新成功');
                        } else if (response.data.code !== 20008) {
                            console.error('浏览记录添加或更新失败:', response.data.msg);
                        }
                    })
                    .catch(error => {
                        console.error('请求失败:', error);
                        _this.$message.error('获取房型信息失败');
                    });
                this.dialogVisible = true;
            },

            // 下单方法
            placeOrder(roomNumber) {
                // 新增确认提示
                if (!confirm('确认提交订单？')) {
                    return;
                }
                if (!this.isLoggedIn) {
                    window.location.href = 'login.html';
                    return;
                }

                if (roomNumber.status === '可用') {
                    const _this = this;
                    axios.post('http://localhost:8080/ProjectRound1_war/client/orderRoom', {
                        clientId: this.client.id,
                        roomId: roomNumber.roomId,
                        roomNumberId: roomNumber.id,
                    }).then(response => {
                        if (response.data.code === 200) {
                            _this.$message.success('下单成功');
                            _this.fetchOrders(); // 刷新订单列表
                            _this.roomNumberDialogVisible = false; // 关闭弹窗
                            _this.dialogVisible = false;
                        } else if (response.data.code === 30004) {
                            _this.$message.error('下单失败，该房间不可用');
                        } else if (response.data.code === 50003) {
                            _this.$message.error('您已被该商家拉黑，不可下单');
                        } else {
                            _this.$message.error('下单失败，请稍后重试');
                        }
                    }).catch(error => {
                        console.error('请求失败:', error);
                        _this.$message.error('下单失败，请稍后重试');
                    });
                } else {
                    this.$message.warning('下单失败，房间不可用');
                }
            },

            // 跳转到支付页面
            goToPayment(order) {
                this.currentOrder = order;
                this.dialogVisibleForPayment = true;
                this.password = '';
            },

            handlePayment() {
                const _this = this;
                axios.post('http://localhost:8080/ProjectRound1_war/user/login',
                    {
                        phoneNum: _this.user.phoneNum,
                        password: _this.password,
                    }
                )
                    .then(response => {
                        if (response.data.code === 200) {
                            _this.payOrder(_this.currentOrder);
                        } else {
                            _this.$message.error('密码错误，请重新输入');
                        }
                    })
                    .catch(error => {
                        console.error('请求失败:', error);
                    });
            },

            //支付
            payOrder(order) {
                const _this = this;
                axios.post('http://localhost:8080/ProjectRound1_war/client/payOrder', order.id)
                    .then(response => {
                        if (response.data.code === 200) {
                            _this.$message.success('支付成功');
                            _this.dialogVisibleForPayment = false;
                            _this.fetchOrders();
                        } else if (response.data.code === 20003) {
                            _this.$message.error('余额不足...');
                        } else if (response.data.code === 40007) {
                            _this.$message.error('该订单已支付过了');
                        } else {
                            _this.$message.error('支付失败，请稍后重试');
                            console.error('支付失败:', response.data.msg);
                        }
                    })
                    .catch(error => {
                        console.error('支付请求失败:', error);
                        _this.$message.error('支付失败，请检查余额后重试');
                    });
            },

            // 取消订单
            cancelOrder(order) {
                if (!confirm('确定要取消该订单吗？')) {
                    return;
                }
                const _this = this;
                axios.post('http://localhost:8080/ProjectRound1_war/client/cancelOrder', order.id)
                    .then(response => {
                        if (response.data.code === 200) {
                            _this.$message.success('订单取消成功');
                            _this.fetchOrders(); // 刷新订单列表
                        } else {
                            _this.$message.error('订单取消失败');
                            console.error('订单取消失败:', response.data.code);
                        }
                    })
                    .catch(error => {
                        console.error('请求失败:', error);
                        _this.$message.error('订单取消失败');
                    })
            },

            // 申请退款
            requestRefund(order) {
                if (!confirm('确定要申请退款吗？')) return

                const _this = this
                axios.post('http://localhost:8080/ProjectRound1_war/client/applyRefund', order.id)
                    .then(response => {
                        if (response.data.code === 200) {
                            _this.$message.success('退款申请已提交')
                            _this.fetchOrders()
                        } else if (response.data.code === 40005) {
                            _this.$message.error('该订单不符合退款条件')
                        } else {
                            _this.$message.error('退款申请失败，请稍后重试')
                            console.error('退款申请失败:', response.data.msg)
                        }
                    })
                    .catch(error => {
                        console.error('请求失败:', error)
                        _this.$message.error('退款请求失败')
                    })
            },

            deleteOrder(order) {
                if (!confirm('删除后无法找回，确定要删除该订单吗？')) {
                    return;
                }
                const _this = this;
                axios.post('http://localhost:8080/ProjectRound1_war/client/deleteOrder', order.id)
                    .then(response => {
                        if (response.data.code === 200) {
                            _this.$message.success('订单删除成功');
                            _this.fetchOrders(); // 刷新订单列表
                        } else {
                            _this.$message.error('订单删除失败');
                            console.error('订单删除失败:', response.data.code);
                        }
                    })
                    .catch(error => {
                        console.error('请求失败:', error);
                        _this.$message.error('订单删除失败');
                    });
            },

            // 打开房间号对话框
            openRoomNumberDialog(row) {
                this.selectedRoom = row;
                this.fetchRoomNumbers(row.id);
                this.roomNumberDialogVisible = true;
            },
            // 获取房间号数据
            fetchRoomNumbers(roomId) {
                const _this = this;
                axios.post('http://localhost:8080/ProjectRound1_war/merchant/getRoomNumbers', roomId)
                    .then(response => {
                        if (response.data.code === 200) {
                            _this.roomNumbers = response.data.data;
                        }
                    }).catch(error => {
                    console.error(error);
                    _this.$message.error('获取房间号数据失败');
                });
            },
        }
    });
</script>
</body>
</html>